package cn.lopr.im.android.mvp.view.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.File;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.OnCallBackListener;
import cn.lopr.im.android.common.app.Activity;
import cn.lopr.im.android.databinding.ActivityRegisterBeforeBinding;
import cn.lopr.im.android.mvp.contact.IRegisterBeforeContact;
import cn.lopr.im.android.mvp.presenter.RegisterBeforePresenterImpl;
import cn.lopr.im.android.utils.GsonUtil;
import cn.lopr.im.android.utils.IDUtil;
import cn.lopr.im.android.utils.PrefUtils;
import cn.lopr.im.android.utils.cos.CosClient;
import cn.lopr.im.android.utils.cos.CosProperties;
import cn.lopr.im.android.utils.cos.MySessionCredentialProvider;


public class RegisterBeforeActivity extends Activity implements IRegisterBeforeContact.IRegisterBeforeView {

    private static final String TAG = "Activity";
    ActivityRegisterBeforeBinding binding;
    //相册请求码
    private static final int ALBUM_REQUEST_CODE = 1;
    //剪裁请求码
    private static final int CROP_SMALL_PICTURE = 2;
    //最后显示的图片文件
    public static String mFile;

    private IRegisterBeforeContact.IRegisterBeforePresenter registerBeforePresenter;
    private MySessionCredentialProvider sessionCredentialProvider;
    private CosProperties cosProperties;
    private CosClient cosClient;
    private String sex = "男";
    private String portrait = null;
    private User reg;

    @Override
    protected View getContentLayoutId() {
        binding = ActivityRegisterBeforeBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initWidget() {
        super.initWidget();

        this.binding.btnSubmit.setOnClickListener(e -> registerBeforePresenter.regBefore());
        this.binding.imSex.setOnClickListener(e -> {
            if (sex.equals("男")) {
                sex = "女";
                binding.imSex.setImageResource(R.drawable.ic_sex_woman);
                //binding.imSex.setBackgroundResource(R.drawable.woman_bg_sex);
            } else {
                sex = "男";
                binding.imSex.setImageResource(R.drawable.ic_sex_man);
                //binding.imSex.setBackgroundResource(R.drawable.man_bg_sex);
            }
        });
        this.binding.imPortrait.setOnClickListener(e -> getPicFromAlbum());
    }

    @Override
    protected void initData() {
        super.initData();
        this.registerBeforePresenter = new RegisterBeforePresenterImpl(this, this);
        this.reg = (User) getIntent().getSerializableExtra("reg");
        this.registerBeforePresenter.getCosTempSecret(new OnCallBackListener<CosProperties, String>() {
            @Override
            public void success(CosProperties data) {
                cosProperties = data;
                sessionCredentialProvider = new MySessionCredentialProvider()
                        .setExpiredTime(data.getExpiredTime())
                        .setStartTime(data.getStartTime())
                        .setTmpSecretId(data.getCredentials().get("tmpSecretId"))
                        .setSessionToken(data.getCredentials().get("sessionToken"))
                        .setTmpSecretKey(data.getCredentials().get("tmpSecretKey"));
            }

            @Override
            public void failure(String errMsg) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ALBUM_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    startPhotoZoom(uri); // 开始对图片进行裁剪处理
                }
                break;
            case CROP_SMALL_PICTURE:    //调用相册后返回
                if (data != null) {
                    Bitmap photo = BitmapFactory.decodeFile(mFile);
                    this.binding.imPortrait.setImageBitmap(photo);
                    this.uploadFile(mFile);
                }
                break;
        }
    }

    @Override
    public void regBeforeSuccess(User user) {
        PrefUtils.setString(this, "phone", getPhone());
        PrefUtils.setString(this, "password", getPassword());
        PrefUtils.setString(this, "user", GsonUtil.objectToJson(user));

        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("user", user);
        this.startActivity(intent);
    }

    @Override
    public void regBeforeFailure(String message) {
        Toast.makeText(RegisterBeforeActivity.this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void saveJwtKey(String token, String value) {
        PrefUtils.setString(this, token, value);
    }

    @Override
    public String getPhone() {
        return reg.getPhone();
    }

    @Override
    public String getPassword() {
        return reg.getPassword();
    }

    @Override
    public String getSex() {
        return this.sex;
    }

    @Override
    public String getPortrait() {
        return this.portrait;
    }

    @Override
    public String getIntroduction() {
        return this.binding.etIntroduction.getText().toString();
    }

    @Override
    public void uploadFile(String path) {
        this.cosClient = new CosClient(this, this.sessionCredentialProvider, this.cosProperties);
        this.cosClient.upload("img/" + IDUtil.getUUID() + ".png", path, null, s -> portrait = s);
    }

    /**
     * 从相册获取图片
     */
    private void getPicFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, ALBUM_REQUEST_CODE);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {

        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", false);
        File out = new File(getPath());
        if (!out.getParentFile().exists()) {
            out.getParentFile().mkdirs();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    //裁剪后的地址
    public String getPath() {
        //resize image to thumb
        if (mFile == null) {
            mFile = Environment.getExternalStorageDirectory() + "/" + "Im/" + "outtemp.png";
        }
        return mFile;
    }
}
